import { Component, Input, OnInit, OnDestroy, ViewChild } from '@angular/core';

import { IonInfiniteScroll } from '@ionic/angular';

import { MessageService } from 'src/app/shared/service/message.service';
import { HttpService } from 'src/app/shared/service/http.service';

import { Subscription } from 'rxjs';

import { EventService } from 'src/app/shared/service/event.service';

import { AppGlobalService } from '../../shared/service/app-global.service';
// import { IonInfiniteScroll } from '@ionic/angular';

@Component({
    selector: 'app-recommend-list',
    templateUrl: './recommend-list.component.html',
    styleUrls: ['./recommend-list.component.scss'],
})
export class RecommendListComponent implements OnInit, OnDestroy {
    @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
    @Input() tagData: any;
    defaultImg = 'assets/img/default_img.png';
    sessionId: string;
    // 声明订阅对象
    subscription: Subscription = null;
    style: any = "background:red,font-siz:20px,color:blue";

    // 筛选及页面数据参数
    params: any = { content: {} };

    // 当前页数，默认1
    pageNo = 1;

    // size
    pageSize: number;

    // 数量
    pageTotal: number;

    listData: any;
    a: any;
    tipsFlag = false;
    constructor(
        private appGlobalService: AppGlobalService,
        private message: MessageService,
        private eventService: EventService,
        private http: HttpService
    ) {
    }
    tempEvent: any;
    clickedOpp: any = "";
    ngOnInit() {
        this.clickedOpp = window.sessionStorage.getItem('clickedOpp');
        if (this.tagData.data.submit && this.tagData.data.data.length === 0 && this.tagData.searchText) {
            this.a = Object.values(JSON.parse(this.tagData.searchText))[0];
        }
        this.sessionId = localStorage.getItem('sessionId');
        if (this.tagData.data.submit !== undefined) {
            // 初始化参数
            this.params = this.tagData.data.submit;
            this.params.sessionId = this.sessionId;

            this.listData = this.tagData.data.data;

            this.pageSize = this.tagData.data.pageSize;
            this.pageTotal = this.tagData.data.pageTotal;
        }

        if (!this.subscription && this.tagData.data.submit !== undefined) {

            // event.target.disabled = true;
            // 获取筛选参数
            this.subscription = this.message.getMessage().subscribe(param => {
                if (this.tempEvent) {
                    this.tempEvent.target.disabled = false;
                }
                // // 重置当前页数
                this.pageNo = 1;
                // 参数
                if (!param) {
                    return;
                }
                this.params.content = param;
                // 页面数据参数
                this.params.content.pageNo = this.pageNo;
                // 请求获取新数据
                this.http.post('application/submit', this.params, res => {
                    // 请求数据成功
                    if (res.success) {
                        const result = res.data.data; // JSON.parse(res.data.data);
                        // 筛选数据
                        this.tagData.data.data = result;
                        this.tagData.data.data.forEach(element => {
                            if (this.clickedOpp && this.clickedOpp.indexOf(element.link.params.opportunity_id) > -1) {
                                element.clicked = true;
                            }
                        });
                    } else {
                        // 请求数据失败
                        this.appGlobalService.showToast(res.message, 2000, 'middle');
                    }
                },
                    err => {
                        // 请求数据失败
                        this.appGlobalService.showToast(err.message, 2000, 'middle');
                    });
            });
        }

        const len = this.tagData.data.data.length;
        // console.log(this.tagData.data, 'tagdddddd');
        if (len > 0) {
            for (let i = 0; i < len; i++) {
                const v = this.tagData.data.data[i];

                if (v.link !== undefined && v.link.params !== undefined) {
                    if (this.clickedOpp && this.clickedOpp.indexOf(v.link.params.opportunity_id) > -1) {
                        v.clicked = true;
                    }
                }
                if (v.images && v.images.imageUrl !== undefined && (v.images.imageUrl + '').startsWith('http')) {
                    let url = v.images.imageUrl ;
                    url = url.replace(';', '');
                    v.images.imageUrl = url;
                }
                this.tagData.data.data[i] = v;
            }

            if (len < 10 && this.tagData.isAutoFillData) {
                for (let i = len; i < 10; i++) {
                    this.tagData.data.data[i] = { images: '', isAutoFillData: true };
                }
            }
        }
        if (len > 0 && len < this.pageSize) {
            this.tipsFlag = true;
        }
    }

    ngOnDestroy(): void {
        sessionStorage.removeItem('showName');
        if (this.tagData.data.submit !== undefined) {
            // 组件生命周期结束的时候，注销
            this.subscription.unsubscribe();
        }
    }


    clickLink(obj) {
        if (!obj) {
            console.log('没有返回link-target');
        }
        const pageParams = {
            pageId: obj.target,
            params: obj.params,
            sessionId: localStorage.getItem('sessionId')
        };
        this.appGlobalService.goToForward(pageParams);
    }

    loadMoreData(event) {
        try {


            this.tempEvent = event;
            if (this.pageNo >= this.pageTotal) {
                event.target.disabled = true;
                // this.appGlobalService.showToast('没有数据了...', 1000, 'middle');
                // event.complete();
                return;
            }
            // // 请求下一个页面
            this.pageNo = this.pageNo + 1;
            // // 参数
            this.params.content.pageNo = this.pageNo;
            // 请求获取新数据
            this.http.post('application/submit', this.params, res => {

                // 请求数据成功
                if (res.success) {
                    const resList = res.data.data;
                    // 追加返回数据
                    if (resList && resList.length > 0) {
                        this.tipsFlag = resList.length < this.pageSize ? true : false;
                        // 追加数据
                        resList.map(v => {
                            if (this.clickedOpp && this.clickedOpp.indexOf(v.link.params.opportunity_id) > -1) {
                                v.clicked = true;
                            }
                            if (v.images && v.images.imageUrl !== undefined && (v.images.imageUrl + '').startsWith('http')) {
                                let url = v.images.imageUrl ;
                                url = url.replace(';', '');
                                v.images.imageUrl = url;
                            }
                            // else if (v.images !== undefined) {
                            //     v.images = { imageUrl: this.defaultImg, isAuthenticated:v.images.isAuthenticated };
                            // }
                            this.tagData.data.data.push(v);
                        });
                    } else {
                        event.target.disabled = true;
                        // 没有数据了
                        // this.appGlobalService.showToast('没有数据了...', 1000, 'middle');
                        this.tipsFlag = true;
                    }
                } else {
                    // 请求失败，更新当前页数
                    this.pageNo = this.pageNo - 1;
                    // 请求数据失败
                    this.appGlobalService.showToast(res.message, 2000, 'middle');
                }
                event.target.complete();

            }, err => {
                // 请求失败，更新当前页数
                this.pageNo = this.pageNo - 1;
                // 请求数据失败
                this.appGlobalService.showToast(err.message, 2000, 'middle');
                event.target.complete();

            });
        } catch (error) {
            console.log('error----->' + JSON.stringify(error));
        }
    }

    doRefresh(event) {
    }

    get(item, obj?) {
        item.clicked = true;
        if (obj) {
            this.clickedOpp = `${this.clickedOpp},${obj.params.opportunity_id}`;
            window.sessionStorage.setItem('clickedOpp', this.clickedOpp);
        }
        if (obj && obj.target === undefined && item.target === undefined) {
            return;
        } else if (obj === undefined && item.target === undefined) {
            return;
        }
        const params = {
            pageId: obj ? obj.target : item.target,
            params: obj ? obj.params : item.params,
            sessionId: this.sessionId
        };
        this.appGlobalService.goToForward(params);
    }

    moreActionClick(obj) {
        this.eventService.eventEmit.emit('searchTabListener', obj);
    }

    getNgStyle(str) {
        try {
            return JSON.parse(str);
        } catch (error) {
            return {};
        }
    }
}
